# -*- coding: utf-8 -*-
"""
@Time : 2024/4/9 14:32
@Author : ChenXiaoliang
@Email : middlegod@sina.com
@File : slide_crypto.py
"""

import base64
import io
import cv2


def get_bg_slide_img(driver):
    bigimg_eleme = driver.find_element_by_class_name("JDJRV-bigimg").find_element_by_tag_name("img")
    bigimg = bigimg_eleme.get_attribute("src")
    img_data = base64.b64decode(bigimg.split(",")[-1])
    img_obj = io.BytesIO(img_data)
    with open("bigimg.png", "wb") as f:
        f.write(img_obj.getvalue())
    smallimg_eleme = driver.find_element_by_class_name("JDJRV-smallimg").find_element_by_tag_name("img")
    smallimg = smallimg_eleme.get_attribute("src")
    img_data = base64.b64decode(smallimg.split(",")[-1])
    img_obj = io.BytesIO(img_data)
    with open("smallimg.png", "wb") as f:
        f.write(img_obj.getvalue())


def get_distance():
    path = "bigimg.png"
    img = cv2.imread(path)

    path = "smallimg.png"
    img2 = cv2.imread(path)

    imgContour = img.copy()
    print("img.shape:", img.shape)
    print("img2.shape:", img2.shape)

    imgGray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    imgBlur = cv2.GaussianBlur(imgGray, (5, 5), 0)
    imgCanny = cv2.Canny(imgBlur, 50, 150)

    imgGray2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
    imgBlur2 = cv2.GaussianBlur(imgGray2, (5, 5), 0)
    imgCanny2 = cv2.Canny(imgBlur2, 50, 150)

    cv2.imshow("O", imgCanny)

    # 匹配拼图
    result = cv2.matchTemplate(imgCanny, imgCanny2, cv2.TM_CCOEFF_NORMED)

    # 归一化
    cv2.normalize(result, result, 0, 1, cv2.NORM_MINMAX, -1)

    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)

    print("min_loc:", min_loc)
    print("max_loc:", max_loc)

    # 匹配后结果画圈
    # 这个(max_loc[0] + 50, max_loc[1] + 50)中的50，是img2的宽w高h
    cv2.rectangle(imgContour, max_loc, (max_loc[0] + 50, max_loc[1] + 50), (0, 0, 255), 2)

    # 原图为360*140 在浏览器resize为242*94.11；这里我们只用到宽。所以需要进行同比例缩放。
    res = max_loc[0] / (360 / 242)

    cv2.imshow("Canny Image", imgContour)
    # 这里不可以用0，因为图片窗口会一直显示，程序卡住无法return出距离给滑块功能使用。
    cv2.waitKey(100)
    print("应滑动距离获取成功。")
    return res


def get_slide_track(distance):
    """
    制造滑块轨迹(必备，否则即使滑动验证码匹配成功，也不会验证通过)
    :param distance: 滑块与背景图缺口之间的offset
    :return:
    """
    v, current = 0, 0
    mid = distance * 3 / 5
    tracks = []
    t = 0.6
    while current < distance:
        if current < round(mid):
            a = 2
        else:
            a = -3
        s = v * t + 0.5 * a * (t ** 2)
        current += s
        v = v + a * t
        tracks.append(round(s))
    return tracks
